"""
此文件用于获取新老目标比对的表格
"""
from CONFIG import repo_list
import xml.etree.ElementTree as ET
import os
import json
import openpyxl
from openpyxl.styles import Alignment


HOME = os.path.dirname(os.path.abspath(__file__))
MANIFEST_HOME = os.path.join(HOME, ".repo", "manifests")
OLD_PRECISE_PATH = os.path.join(HOME, "test", "xts", "tools", "config", "precise_compilation.json")
ACTS_HOME = os.path.join(HOME, "test", "xts", "acts")


import sys
CI_HOME = os.path.join(HOME, "test", "xts", "tools", "ci")
sys.path.append(CI_HOME)
from Utils import ChangeFileEntity, XTSTargetUtils, PathUtils, HOME
from ci_manager import ComponentManager, XTSManager, OldPreciseManager


XTS_REPO = {
    "xts_acts",
    "xts_dcts",
    "xts_hats",
    "xts_tools"
}

class ResultClass():
    def __init__(self, repo_name):
        self.repo_name = repo_name
        self.path = ""
        self.oldtarget = ""
        self.bundlename = ""
        self.newTarget = []


def init_result_map(repo_list):
    result_map = {}
    for repo in repo_list:
        result_map[repo] = ResultClass(repo)
    return result_map


def get_repo_path_map_impl(manifest_home, bundle_path_repo_map, reslultclass_map):
    # print(manifest_home)

    # 遍历XML文件内容
    manifest_xml_list = [manifest_home]
    for xml in manifest_xml_list:
        root = ET.parse(xml).getroot()
        if root.find('include') is not None:
            # print ("in include")
            for child in root.findall('include'):
                # get_repo_path_map_impl(os.path.join(MANIFEST_HOME, child.attrib['name']), bundle_path_repo_map)
                get_repo_path_map_impl(os.path.join(MANIFEST_HOME, child.attrib['name']), bundle_path_repo_map ,reslultclass_map)
        else:
            # print ("in else")
            for child in ET.parse(xml).getroot().findall('project'):
                if "lite" in child.attrib['path']:
                    continue
                repo_name = child.attrib['name']
                # print('仓名' + repo_name)

                path = child.attrib['path']
                if repo_name in reslultclass_map:
                    reslultclass_map[repo_name].path = path



def get_repo_path_map(manifest_home, reslultclass_map):
    bundle_path_repo_map = {}
    get_repo_path_map_impl(manifest_home, bundle_path_repo_map, reslultclass_map)
    return bundle_path_repo_map

not_in_result_class = []
def get_old_target(reslultclass_map, path=OLD_PRECISE_PATH):
    # target-pathtarget
    path_temp = {}
    with open(path, 'r') as file:
        rules_data = json.load(file)
    for m in rules_data:
        n = m["name"]
        tar = m["buildTarget"]
        if n not in reslultclass_map:
            not_in_result_class.append(n)
            print(f"error: {n} 仓不存在或不参与xts门禁构建")
            return
        # 获取buildTarget 路径
        if "test/xts/acts" in tar:
            reslultclass_map[n].oldtarget = tar
        elif tar in path_temp:
            reslultclass_map[n].oldtarget = path_temp[tar]
        else:
            match_str = f'group("{tar}")'
            for root, dirs, files in os.walk(ACTS_HOME):
                # Calculate the depth of the current directory relative to the root
                depth = root.replace(ACTS_HOME, '').count(os.sep)
                if depth > 2:
                    # If we've gone deeper than 2 levels, stop walking
                    dirs.clear()
                for file in files:
                    if file == 'BUILD.gn':
                        file_path = os.path.join(root, file)
                        with open(file_path, 'r', encoding='utf-8') as f:
                            file_content = f.read()

                            #print("file_content" + file_content)
                            if match_str in file_content:

                                re_path = root.replace(HOME, "")
                                path_target = f"{re_path}:{tar}"
                                path_temp[tar] = path_target
                                reslultclass_map[n].oldtarget = path_target

def get_bundle_name_bypath(path):
    bundle_path = os.path.join(path, "bundle.json")
    if os.path.exists(bundle_path):

        with open(bundle_path, 'r') as json_file:
            data = json.load(json_file)
            # 尝试获取 "component" 对象里的 "name" 字段
            component = data.get("component")
            if component and isinstance(component, dict):
                component_name = component.get("name")
                # 如果找到了 "name" 字段，返回
                if component_name:
                    return component_name
    return None


def get_new_target(reslultclass_map):
    sum = len(reslultclass_map)
    count = 0
    for repo  in reslultclass_map:
        count += 1
        print(f'{count}/{sum}')
        if count > 3:
            return
        bundle_name = reslultclass_map[repo].bundlename

        paths = XTSTargetUtils.getPathsByBundle(bundle_name, ACTS_HOME)
        targets = set()
        if paths:
            sum_path = PathUtils.removeSubandDumpPath(list(paths))
            for path in sum_path:
                targets.update(set(XTSTargetUtils.getTargetfromPath(ACTS_HOME, path)))
            reslultclass_map[repo].newTarget = list(targets)

def write_excel(reslultclass_map):
    # 创建一个新的工作簿
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Results"

    # 写入表头
    header = ["Repo Name", "Path", "Old Target", "Bundle Name", "New Target"]
    ws.append(header)

    # 写入数据
    for repo in reslultclass_map:
        row = [
            reslultclass_map[repo].repo_name,
            reslultclass_map[repo].path,
            reslultclass_map[repo].oldtarget,
            reslultclass_map[repo].bundlename,
            "\n".join(reslultclass_map[repo].newTarget)  # 将 newTarget 列表中的每一项用换行符连接
        ]
        ws.append(row)

    # 设置 "New Target" 列的对齐方式为居中，并且允许文本换行
    for row in ws.iter_rows(min_row=2, max_col=5):
        cell = row[4]  # 第五列（即 "New Target" 列）
        cell.alignment = Alignment(wrap_text=True)

    # 调整行高和列宽
    for row in ws.iter_rows():
        ws.row_dimensions[row[0].row].height = 30
    for col in range(1, ws.max_column + 1):
        ws.column_dimensions[openpyxl.utils.get_column_letter(col)].width = 20

    # 保存工作簿
    wb.save("results.xlsx")

# repo-oldtarget-bundlename-新目标(list)
def run():
    # 获取全部跑xts门禁的repo,构造存储结果的map
    reslultclass_map = init_result_map(repo_list)
    # 匹配path
    get_repo_path_map(os.path.join(os.path.dirname(MANIFEST_HOME), "manifest.xml"), reslultclass_map)
    # 匹配老target
    get_old_target(reslultclass_map)
    # 获取bundle_name
    null_bundle_name = []
    for repo in reslultclass_map:
        path = reslultclass_map[repo].path
        bundle_name = get_bundle_name_bypath(path)
        reslultclass_map[repo].bundlename = bundle_name
        if not bundle_name :
            null_bundle_name.append(repo)
    print(f"@@@@@@@@@@@@@@@@@@ not_in_result_class:")
    not_in_result_class_str = '\n'.join(not_in_result_class)
    print(f"{not_in_result_class_str}")
    print(f"@@@@@@@@@@@@@@@@@@ null_bundle_name:")
    null_bundle_name_str = '\n'.join(null_bundle_name)
    print(f"{null_bundle_name_str}")
    # 获取新target
    get_new_target(reslultclass_map)
    # 写excle
    write_excel(reslultclass_map)

if __name__ == '__main__':
    run()
